<?php
require("LRCMetaDataParser.php");
require("Utils.php");
require("DatabaseLib.php");
require("lrcStoringFilter.php");

/*echo("Script disabled!");

die();*/

function clearAndSaveLRC($db,&$lrcfile,$filename,$autor)
{
	$destFolder = "uploadedLrc/";
	$artist = NULL;
	$title = NULL;
	$artist_title_pair = trim($filename);
	if(Utils::str_i_ends_with($artist_title_pair,".lrc"))
		$artist_title_pair = substr($artist_title_pair,0,strlen($artist_title_pair)-4);
	if(strpos($artist_title_pair,"-") === FALSE)
		$title = $artist_title_pair;
	else
		list($artist,$title) = explode("-",$artist_title_pair,2);
	$artist = ($artist != NULL ? ucwords(strtolower(trim($artist))) : NULL);
	$title = ($title != NULL ? ucwords(strtolower(trim($title))) : NULL);

	$metas = array();
	$metas[LRCMetaDataParser::$META_DATA_TITLE] = $title;
	$metas[LRCMetaDataParser::$META_DATA_ARTIST] = $artist;
	$lrcfile = filterLrcFile($lrcfile);//elimina i testi non permessi ed eventuali sponsor
	$metas = LRCMetaDataParser::parseLRCData($lrcfile,$metas);
	$metas[LRCMetaDataParser::$META_DATA_BY] = "www.antosdr.it/KaraokeSingMe";
	if($autor != NULL)
		$metas[LRCMetaDataParser::$META_DATA_AUTOR] = str_replace("]","",trim($autor));
	$mod = false;
	$lrcfile = LRCMetaDataParser::updateLRCData($lrcfile,$metas,$mod,false,true);

	$metas[LRCMetaDataParser::$META_DATA_ARTIST] = ($metas[LRCMetaDataParser::$META_DATA_ARTIST] != NULL ? ucwords(strtolower(trim($metas[LRCMetaDataParser::$META_DATA_ARTIST]))) : NULL);
	$metas[LRCMetaDataParser::$META_DATA_TITLE] = ($metas[LRCMetaDataParser::$META_DATA_TITLE] != NULL ? ucwords(strtolower(trim($metas[LRCMetaDataParser::$META_DATA_TITLE]))) : NULL);

	$finalfname = $metas[LRCMetaDataParser::$META_DATA_ARTIST]." - ".$metas[LRCMetaDataParser::$META_DATA_TITLE].".lrc";
	$finalfname = $destFolder.Utils::normalizeFilename($finalfname);

	if($finalfname == $destFolder." - .lrc")
		return FALSE;

	if($db->GetRecordsNum("UploadedLyrics"," URL = '".addslashes($finalfname)."' ") > 0)
		return FALSE;

	if(@file_put_contents(getcwd()."/".$finalfname,$lrcfile) === FALSE)
	{
		return FALSE;
	}

	//add to db
	$ti = $metas[LRCMetaDataParser::$META_DATA_TITLE];
	$ar = $metas[LRCMetaDataParser::$META_DATA_ARTIST];
	$al = $metas[LRCMetaDataParser::$META_DATA_ALBUM];
	$la = $metas[LRCMetaDataParser::$META_DATA_LANGUAGE];
	if(!$db->AddRecord("UploadedLyrics","URL, Title, Artist, Album, Language",
		 "'".addslashes($finalfname)."', ".
		(isset($ti) && $ti != null ? "'".addslashes($ti)."'" : "NULL").", ".
		(isset($ar) && $ar != null ? "'".addslashes($ar)."'" : "NULL").", ".
		(isset($al) && $al != null ? "'".addslashes($al)."'" : "NULL").", ".
		(isset($la) && $la != null ? "'".addslashes($la)."'" : "NULL")))
	{
		unlink(getcwd()."/".$finalfname);
		return FALSE;
	}
	else
	{
		return TRUE;
	}
}

//se ha valori mm:ss.cc o mm:ss
function is_correctly_encoded(&$data)
{
	//regexpr /(\d\d)\:(\d\d)\.(\d\d)/
	//$searchPattern = "/[0-9][0-9]:[0-9][0-9]\.[0-9][0-9]/";
	$searchPattern = "/\[[0-9][0-9]\:[0-9][0-9]/";
	return preg_match($searchPattern,$data);//(preg_match($searchPattern,$data) || preg_match($searchPattern2,$data));
}

function file_get_contents_utf8($fn)
{
	$content = @file_get_contents($fn);
	if($content === FALSE)
		return FALSE;
	$enc = LRCMetaDataParser::getCharSetEncoding($content);
	if(!is_array($enc))//trovato
		return mb_convert_encoding($content, 'UTF-8', $enc);
	else
	{
		if(is_correctly_encoded($content))
			return $content;
		else//probabilmente un dobbio byte char set (UCS-2 o UTF-16)
		{
			$newdat = mb_convert_encoding($content, 'UTF-8', 'UCS-2');
			if(is_correctly_encoded($newdat))
				return $newdat;
			$newdat = mb_convert_encoding($content, 'UTF-8', 'UTF-16');
			if(is_correctly_encoded($newdat))
				return $newdat;
			$encdect = mb_detect_encoding($content,$enc);
			if($encdect !== FALSE)
				return mb_convert_encoding($content, 'UTF-8', $encdect);
		}
	}
	return $content;
}

ini_set("mbstring.func_overload",6);

$db = new DatabaseManager();
$db->Connect();

$file = current($_FILES);

if($file === FALSE)
{
	echo("Sorry, something goes wrong... Upload failed!");
}
else
{

	if($file["size"] > 51200)//se la dimensione è maggiore di 50 KB il caricamento fallisce
	{
		echo("$name: Sorry, the uploaded file is too big! (Max 50KB) Upload failed!");
	}
	else
	{
		$name = basename($file["name"]);
		$ext = strtolower(Utils::get_extension($name));
		if($ext == ".lrc")
		{
			$data = file_get_contents_utf8($file["tmp_name"]);//@file_get_contents($file["tmp_name"]);
			if($data === FALSE)
			{
				echo("$name: Sorry, something goes wrong... Upload failed! Loading file failed!");
			}
			else
			{
				if(clearAndSaveLRC($db,$data,$name, isset($_POST["signature"]) ? $_POST["signature"] : NULL))
					echo("$name: Upload succeeded! Thank you for your contribution!");
				else
					echo("$name: Sorry, something goes wrong... Upload failed!");
			}
		}
		else
			echo("$name: Sorry, the uploaded file is invalid! Only lrc files are allowed!");
	}

}

?>
